using System;
using System.Collections.Generic;
using muduoDotNet;
using muduoDotNet.Messages;
using Google.Protobuf;

namespace muduoDotNet.Examples.ReflectionProtocol{
    /// <summary>
    /// 反射协议服务器示例
    /// 演示如何使用反射特性自动注册和处理协议消息
    /// </summary>
    public class ReflectionProtocolServerExample
    {
        /// <summary>
        /// 运行服务器示例
        /// </summary>
        public static void RunExample()
        {
            Logger.Info("=== Reflection Protocol Server Example ===");
            
            var example = new ReflectionProtocolServerExample();
            example.Start();
            
            Logger.Info("Server running. Press Enter to stop...");
            Console.ReadLine();
            
            example.Stop();
            Logger.Info("Server stopped.");
        }
        
        /// <summary>
        /// 停止服务器
        /// </summary>
        public void Stop()
        {
            if (_server != null)
            {
                _server.Stop();
            }
            Logger.Info("Server shutdown completed.");
        }
        
        private TcpServer _server;
        private Dictionary<TcpConnection, CustomBusinessHandler> _connectionHandlers = new Dictionary<TcpConnection, CustomBusinessHandler>();
        private int _totalConnections = 0;
        private int _maxConnections = 0;
        private EventLoop _loop;

        /// <summary>
        /// 启动反射协议服务器
        /// </summary>
        public void Start()
        {
            Logger.Info("Starting Reflection Protocol Server Example...");
            Init();
        }

        /// <summary>
        /// 初始化服务器
        /// </summary>
        private void Init()
        {
            // 创建事件循环
            var loop = new EventLoop();
            
            // 创建TCP服务器
            _server = new TcpServer(loop, new IPEndPoint(IPAddress.Any, 8888));
            
            // 设置连接回调
            _server.ConnectionCallback = OnConnection;
            
            // 设置消息回调
            _server.MessageCallback = OnMessage;
            
            // 设置写完成回调
            _server.WriteCompleteCallback = OnWriteComplete;
            
            // TcpServer类不支持SetThreadNum方法，它在构造函数中已经使用单个EventLoop
            
            // 启动服务器
            _server.Start();
            
            Logger.Info($"Server listening on {_server.ListenAddr.Address}:{_server.ListenAddr.Port}");
            Logger.Info("Reflection Protocol Server started. Press any key to exit...");
            
            // 注册服务器状态打印定时器
            loop.AddTimer(PrintServerStatus, 5.0, 5.0);
            
            // 启动事件循环已经在TcpServer.Start()中完成
        }

        /// <summary>
        /// 连接建立/断开回调
        /// </summary>
        private void OnConnection(TcpConnection connection)
        {
            if (connection.State == TcpConnectionState.Connected)
            {
                // 连接建立：为每个连接创建一个业务处理器实例
                var handler = new CustomBusinessHandler();
                
                // 消息处理器在构造函数中已经自动注册
                
                // 存储连接与处理器的映射关系
                lock (_connectionHandlers)
                {
                    _connectionHandlers[connection] = handler;
                    _totalConnections++;
                    _maxConnections = Math.Max(_maxConnections, _totalConnections);
                }
                
                Logger.Info($"Connection established: {connection.Name} from {connection.RemoteEndPoint} -> {connection.LocalEndPoint}");
                Logger.Info($"Active connections: {_totalConnections}, Max connections: {_maxConnections}");
                
                // 发送欢迎消息
                var welcomeMessage = new StatusMessage
                {
                    Type = StatusMessage.Types.StatusType.Info,
                    Message = "Welcome to Reflection Protocol Server!",
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                welcomeMessage.Metadata.Add("server_name", "ReflectionProtocolServer");
                welcomeMessage.Metadata.Add("protocol_type", "reflection_based");
                welcomeMessage.Metadata.Add("supported_messages", string.Join(", ", handler.GetRegisteredMessageTypes()));
                
                connection.SendProtobufMessage(welcomeMessage);
            }
            else
            {
                // 连接断开：清理业务处理器
                lock (_connectionHandlers)
                {
                    if (_connectionHandlers.TryGetValue(connection, out var handler))
                    {
                        // 打印该连接的业务处理统计信息
                        Logger.Info(handler.GetStatistics());
                        
                        _connectionHandlers.Remove(connection);
                        _totalConnections--;
                    }
                }
                
                Logger.Info($"Connection closed: {connection.Name}");
                Logger.Info($"Active connections: {_totalConnections}");
            }
        }

        /// <summary>
        /// 消息接收回调
        /// </summary>
        private void OnMessage(TcpConnection connection, Buffer buffer)
        {
            // 从缓冲区读取数据并解码，然后交给业务处理器处理
            // 这里简化处理，实际应用中应该根据具体的协议格式进行解码
            
            // 查找该连接对应的业务处理器
            if (_connectionHandlers.TryGetValue(connection, out var handler))
            {
                // 实际应用中应该根据协议格式从buffer中解析出IMessage对象
                // 这里为了演示，我们只记录接收的字节数
                Logger.Debug($"Received {buffer.ReadableBytes} bytes from {connection.Name}");
                
                // 注意：在实际应用中，您应该实现一个完整的协议解码逻辑
                // 这里我们只是展示框架结构
            }
        }

        /// <summary>
        /// 写入完成回调
        /// </summary>
        private void OnWriteComplete(TcpConnection connection)
        {
            Logger.Debug($"Write complete for {connection.Name}");
        }

        /// <summary>
        /// 打印服务器状态信息
        /// </summary>
        private void PrintServerStatus()
        {
            Logger.Info($"Server status - Active connections: {_totalConnections}, Max connections: {_maxConnections}");
            
            // 统计所有连接的业务处理器状态
            int totalHandlers = 0;
            int totalEchoRequests = 0;
            int totalHeartbeats = 0;
            int totalStatusMessages = 0;
            int totalUnhandledMessages = 0;
            
            lock (_connectionHandlers)
            {
                totalHandlers = _connectionHandlers.Count;
                
                foreach (var handler in _connectionHandlers.Values)
                {
                    // 这里应该实现更好的方式来获取处理器的统计信息
                    // 为了简化，我们只记录处理器数量
                }
            }
            
            Logger.Info($"Total message handlers: {totalHandlers}");
            Logger.Info($"Message statistics: EchoRequests={totalEchoRequests}, Heartbeats={totalHeartbeats}, StatusMessages={totalStatusMessages}, Unhandled={totalUnhandledMessages}");
        }
    }
}